<template>
  <div class="tcp-client module-container">
    <div class="module-header">
      <h2>{{ $t('tcpClient.title') }}</h2>
      <p class="module-description">{{ $t('tcpClient.description') }}</p>
    </div>

    <div class="module-content">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="connection-card">
            <div slot="header" class="card-header">
              <span>{{ $t('tcpClient.connection') }}</span>
              <ConnectionStatus :connected="connected" />
            </div>

            <el-form label-position="top" size="small">
              <el-form-item :label="$t('tcpClient.host')">
                <el-input
                  v-model="config.host"
                  :disabled="connected"
                  placeholder="127.0.0.1"
                  prefix-icon="el-icon-location"
                />
              </el-form-item>

              <el-form-item :label="$t('tcpClient.port')">
                <el-input-number
                  v-model="config.port"
                  :min="1"
                  :max="65535"
                  :disabled="connected"
                  style="width: 100%"
                />
              </el-form-item>

              <el-form-item :label="$t('tcpClient.encoding')">
                <el-select v-model="config.encoding" :disabled="connected" style="width: 100%">
                  <el-option value="utf8" label="UTF-8" />
                  <el-option value="hex" label="HEX" />
                  <el-option value="base64" label="Base64" />
                  <el-option value="ascii" label="ASCII" />
                </el-select>
              </el-form-item>

              <el-form-item :label="$t('tcpClient.lineEnding')">
                <el-select v-model="config.lineEnding" style="width: 100%">
                  <el-option value="none" :label="$t('tcpClient.none')" />
                  <el-option value="n" label="\n (LF)" />
                  <el-option value="rn" label="\r\n (CRLF)" />
                  <el-option value="r" label="\r (CR)" />
                </el-select>
              </el-form-item>

              <el-form-item>
                <el-button
                  v-if="!connected"
                  type="primary"
                  icon="el-icon-link"
                  style="width: 100%"
                  @click="connect"
                >
                  {{ $t('tcpClient.connect') }}
                </el-button>
                <el-button
                  v-else
                  type="danger"
                  icon="el-icon-disconnect"
                  style="width: 100%"
                  @click="disconnect"
                >
                  {{ $t('tcpClient.disconnect') }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>

          <el-card class="send-card">
            <div slot="header">
              <span>{{ $t('tcpClient.sendData') }}</span>
            </div>

            <el-form label-position="top" size="small">
              <el-form-item>
                <el-input
                  v-model="messageInput"
                  type="textarea"
                  :rows="6"
                  :placeholder="$t('tcpClient.enterMessage')"
                  :disabled="!connected"
                />
              </el-form-item>

              <el-form-item>
                <el-checkbox v-model="hexInput">{{ $t('tcpClient.hexInput') }}</el-checkbox>
              </el-form-item>

              <el-form-item>
                <el-button
                  type="primary"
                  icon="el-icon-s-promotion"
                  :disabled="!connected || !messageInput"
                  style="width: 100%"
                  @click="sendMessage"
                >
                  {{ $t('tcpClient.send') }}
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <el-col :span="16">
          <el-card class="messages-card">
            <div slot="header" class="messages-header">
              <span>{{ $t('tcpClient.messages') }}</span>
              <div class="messages-toolbar">
                <el-checkbox v-model="autoScroll">{{ $t('common.autoScroll') }}</el-checkbox>
                <el-button size="mini" @click="clearMessages">{{ $t('common.clear') }}</el-button>
                <el-button size="mini" @click="exportMessages">{{ $t('common.export') }}</el-button>
              </div>
            </div>

            <div class="messages-container" ref="messagesContainer">
              <div v-if="messages.length === 0" class="no-messages">
                <i class="el-icon-chat-line-round"></i>
                <p>{{ $t('tcpClient.noMessages') }}</p>
              </div>
              
              <div v-else class="messages-list">
                <div
                  v-for="msg in messages"
                  :key="msg.id"
                  :class="['message-item', `message-${msg.type}`, `message-${msg.direction}`]"
                >
                  <div class="message-header">
                    <span class="message-time">{{ formatTime(msg.timestamp) }}</span>
                    <el-tag 
                      :type="msg.direction === 'in' ? 'success' : msg.direction === 'out' ? 'primary' : 'info'"
                      size="mini"
                    >
                      {{ msg.direction === 'in' ? $t('tcpClient.received') : 
                         msg.direction === 'out' ? $t('tcpClient.sent') : 
                         $t('tcpClient.system') }}
                    </el-tag>
                    <span v-if="msg.source" class="message-source">{{ msg.source }}</span>
                  </div>
                  <div class="message-content">
                    <pre>{{ msg.content }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </el-card>

          <el-card class="statistics-card">
            <div slot="header">
              <span>{{ $t('tcpClient.statistics') }}</span>
            </div>
            <el-row :gutter="20">
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ statistics.sent }}</div>
                  <div class="stat-label">{{ $t('tcpClient.messagesSent') }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ statistics.received }}</div>
                  <div class="stat-label">{{ $t('tcpClient.messagesReceived') }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ formatBytes(statistics.bytesSent) }}</div>
                  <div class="stat-label">{{ $t('tcpClient.bytesSent') }}</div>
                </div>
              </el-col>
              <el-col :span="6">
                <div class="stat-item">
                  <div class="stat-value">{{ formatBytes(statistics.bytesReceived) }}</div>
                  <div class="stat-label">{{ $t('tcpClient.bytesReceived') }}</div>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import ConnectionStatus from '../../components/ConnectionStatus.vue'

export default {
  name: 'TcpClient',
  
  components: {
    ConnectionStatus
  },

  data() {
    return {
      messageInput: '',
      hexInput: false,
      autoScroll: true,
      statistics: {
        sent: 0,
        received: 0,
        bytesSent: 0,
        bytesReceived: 0
      }
    }
  },

  computed: {
    ...mapState('tcpUdp', {
      storeMessages: 'messages'
    }),
    ...mapGetters('tcpUdp', ['tcpClientConfig', 'tcpConnected']),
    
    config: {
      get() {
        return this.tcpClientConfig
      },
      set(value) {
        this.$store.commit('tcpUdp/SET_TCP_CLIENT_CONFIG', value)
      }
    },
    
    connected() {
      return this.tcpConnected
    },
    
    messages() {
      return this.storeMessages.filter(msg => msg.protocol === 'tcp' && msg.mode === 'client')
    }
  },

  watch: {
    messages: {
      handler() {
        this.updateStatistics()
        if (this.autoScroll) {
          this.$nextTick(() => {
            const container = this.$refs.messagesContainer
            if (container) {
              container.scrollTop = container.scrollHeight
            }
          })
        }
      },
      deep: true
    }
  },

  mounted() {
    this.initializeListeners()
  },

  // Removed beforeDestroy to keep client connection when switching pages
  // beforeDestroy() {
  //   if (this.connected) {
  //     this.disconnect()
  //   }
  // },

  methods: {
    ...mapActions('tcpUdp', [
      'connectTcpClient',
      'disconnectTcpClient',
      'handleIncomingMessage'
    ]),

    async connect() {
      try {
        await this.connectTcpClient()
        this.$message.success(this.$t('tcpClient.connectionSuccess'))
      } catch (error) {
        this.$message.error(this.$t('tcpClient.connectionFailed') + ': ' + error.message)
      }
    },

    async disconnect() {
      try {
        await this.disconnectTcpClient()
        this.$message.info(this.$t('tcpClient.disconnected'))
      } catch (error) {
        this.$message.error(error.message)
      }
    },

    async sendMessage() {
      if (!this.messageInput) return

      let message = this.messageInput
      if (this.hexInput) {
        message = this.hexToBuffer(message)
      }

      try {
        await this.$store.dispatch('tcpUdp/sendTcpMessage', {
          message,
          target: null
        })
        this.messageInput = ''
      } catch (error) {
        this.$message.error(this.$t('tcpClient.sendFailed') + ': ' + error.message)
      }
    },

    clearMessages() {
      this.$store.commit('tcpUdp/CLEAR_MESSAGES')
      this.resetStatistics()
    },

    exportMessages() {
      const data = JSON.stringify(this.messages, null, 2)
      const blob = new Blob([data], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `tcp-client-messages-${Date.now()}.json`
      a.click()
      URL.revokeObjectURL(url)
    },

    formatTime(timestamp) {
      const date = new Date(timestamp)
      return date.toLocaleTimeString()
    },

    formatBytes(bytes) {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    hexToBuffer(hexString) {
      const hex = hexString.replace(/\s/g, '')
      const bytes = []
      for (let i = 0; i < hex.length; i += 2) {
        bytes.push(parseInt(hex.substr(i, 2), 16))
      }
      return Buffer.from(bytes)
    },

    updateStatistics() {
      const messages = this.filteredMessages
      this.statistics.sent = messages.filter(m => m.direction === 'out').length
      this.statistics.received = messages.filter(m => m.direction === 'in').length
      
      this.statistics.bytesSent = messages
        .filter(m => m.direction === 'out')
        .reduce((sum, m) => sum + (m.content ? m.content.length : 0), 0)
      
      this.statistics.bytesReceived = messages
        .filter(m => m.direction === 'in')
        .reduce((sum, m) => sum + (m.content ? m.content.length : 0), 0)
    },

    resetStatistics() {
      this.statistics = {
        sent: 0,
        received: 0,
        bytesSent: 0,
        bytesReceived: 0
      }
    },

    initializeListeners() {
      const { tcpUdp } = require('../../utils/electron')
      
      tcpUdp.onTcpData((data) => {
        this.handleIncomingMessage({
          protocol: 'tcp',
          mode: 'client',
          message: data.message,
          source: data.source
        })
      })

      tcpUdp.onTcpError((error) => {
        this.$message.error('TCP Error: ' + error.message)
      })

      tcpUdp.onTcpDisconnected(() => {
        this.$store.commit('tcpUdp/SET_TCP_CLIENT_CONNECTED', false)
        this.$message.warning(this.$t('tcpClient.connectionLost'))
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.tcp-client {
  .connection-card {
    margin-bottom: $spacing-medium;
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .send-card {
    margin-bottom: $spacing-medium;
  }

  .messages-card {
    height: 500px;
    margin-bottom: $spacing-medium;
    
    .messages-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .messages-toolbar {
        display: flex;
        gap: $spacing-small;
        align-items: center;
      }
    }

    .messages-container {
      height: 400px;
      overflow-y: auto;
      background: $background-color-base;
      border-radius: $border-radius-base;
      padding: $spacing-medium;

      .no-messages {
        text-align: center;
        color: $text-regular;
        padding: $spacing-extra-large;
        
        i {
          font-size: 48px;
          color: $text-placeholder;
          margin-bottom: $spacing-medium;
        }
      }

      .messages-list {
        display: flex;
        flex-direction: column;
      }

      .message-item {
        margin-bottom: $spacing-medium;
        padding: $spacing-small $spacing-medium;
        border-radius: $border-radius-base;
        border-left: 3px solid transparent;
        background: $card-bg;

        &.message-in {
          border-left-color: $success-color;
        }

        &.message-out {
          border-left-color: $primary-color;
        }

        &.message-system {
          border-left-color: $info-color;
          background: $info-light;
        }

        .message-header {
          display: flex;
          gap: $spacing-small;
          align-items: center;
          margin-bottom: $spacing-small;
          font-size: 12px;

          .message-time {
            color: $text-secondary;
          }

          .message-source {
            color: $text-secondary;
            margin-left: auto;
          }
        }

        .message-content {
          pre {
            margin: 0;
            font-family: 'Monaco', 'Menlo', monospace;
            font-size: 13px;
            line-height: 1.5;
            white-space: pre-wrap;
            word-break: break-all;
            color: $text-primary;
          }
        }
      }
    }
  }

  .statistics-card {
    .stat-item {
      text-align: center;
      padding: $spacing-medium 0;

      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: $primary-color;
        margin-bottom: $spacing-small;
      }

      .stat-label {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }
}
</style>